package com.candy.codegen.util;


import cn.hutool.core.util.IdUtil;
import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONObject;
import com.candy.codegen.config.GenConfig;
import com.candy.codegen.constant.GenConstants;
import com.candy.codegen.domain.vo.GenTableColumnVO;
import com.candy.codegen.domain.vo.GenTableVO;
import lombok.extern.slf4j.Slf4j;
import org.apache.velocity.VelocityContext;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.*;

/**
 * 代码模版工具类
 *
 * @author rong xi
 * @date 2023/09/14 10:27
 * @version 1.0
 */
@Slf4j
public class VelocityUtils {
    /**
     * 项目空间路径
     */
    private static final String PROJECT_PATH = "src/main/java";

    /**
     * mybatis空间路径
     */
    private static final String MYBATIS_PATH = "src/main/resources/mapper";

    /**
     * html空间路径
     */
    private static final String TEMPLATES_PATH = "src/main/resources/templates";

    /**
     * 默认上级菜单，系统工具
     */
    private static final String DEFAULT_PARENT_MENU_ID = "3";

    /**
     * 设置模板变量信息
     *
     * @return 模板列表
     */
    public static VelocityContext prepareContext(GenTableVO genTable) {
        //模块名 可理解为子系统名，例如 system
        String moduleName = genTable.getModuleName();
        //业务名 可理解为功能英文名，例如 user
        String businessName = genTable.getBusinessName();
        //包名
        String packageName = genTable.getPackageName();
        //使用的模板类型 （crud单表操作 tree树表操作 sub主子表操作）
        String tplCategory = genTable.getTplCategory();
        //功能名 用作类描述，例如 用户
        String functionName = genTable.getFunctionName();
        Map<String,Object> contextMap = new HashMap<>();

        //模版类型
        contextMap.put("tplCategory", tplCategory);
        //表名称
        contextMap.put("tableName", genTable.getTableName());
        //表定义
        contextMap.put("tableDef",genTable.getTableName().toUpperCase());
        //数据库名
        contextMap.put("tableSchema",genTable.getTableSchema());
        //业务名
        contextMap.put("functionName", StringUtils.isNotEmpty(functionName) ? functionName : "【请填写功能名称】");
        //类名
        contextMap.put("ClassName", genTable.getClassName());
        //首字母小写
        contextMap.put("className", StringUtils.uncapitalize(genTable.getClassName()));
        //模块名
        contextMap.put("moduleName", moduleName);
        //业务名
        contextMap.put("businessName", businessName);
        //基础包名
        contextMap.put("basePackage", getPackagePrefix(packageName));
        //包名
        contextMap.put("packageName", packageName);
        //作者
        contextMap.put("author", genTable.getFunctionAuthor());
        //日期
        contextMap.put("datetime", LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy/MM/dd HH:mm")));
        //主键
        contextMap.put("pkColumn", genTable.getPkColumn());
        //根据列类型获取导入包
        contextMap.put("importList", getImportList(genTable));
        //权限前缀
        contextMap.put("permissionPrefix", getPermissionPrefix(moduleName, businessName));
        //字段
        contextMap.put("columns", genTable.getColumns());
        //表
        contextMap.put("table", genTable);
        contextMap.put("menuId", IdUtil.getSnowflakeNextId());

        setMenuVelocityContext(contextMap, genTable);
        if (GenConstants.TPL_TREE.equals(tplCategory)) {
            setTreeVelocityContext(contextMap, genTable);
            contextMap.put("isTree",true);
        }
        if (GenConstants.TPL_SUB.equals(tplCategory)) {
            setSubVelocityContext(contextMap, genTable);
        }
        log.info("VelocityContext:{}",JSON.toJSONString(contextMap));
        return new VelocityContext(contextMap);
    }

    public static void setMenuVelocityContext(Map<String,Object> context, GenTableVO genTable) {
        String options = genTable.getOptions();
        JSONObject paramsObj = JSONObject.parseObject(options);
        String parentMenuId = getParentMenuId(paramsObj);
        context.put("parentMenuId", parentMenuId);
    }

    public static void setTreeVelocityContext(Map<String,Object> context, GenTableVO genTable) {
        String options = genTable.getOptions();
        JSONObject paramsObj = JSONObject.parseObject(options);
        String treeCode = getTreecode(paramsObj);
        String treeParentCode = getTreeParentCode(paramsObj);
        String treeName = getTreeName(paramsObj);
        context.put("treeCode", treeCode);
        context.put("treeParentCode", treeParentCode);
        context.put("treeName", treeName);
        context.put("expandColumn", getExpandColumn(genTable));
        if (paramsObj.containsKey(GenConstants.TREE_PARENT_CODE)) {
            context.put("tree_parent_code", paramsObj.getString(GenConstants.TREE_PARENT_CODE));
        }
        if (paramsObj.containsKey(GenConstants.TREE_NAME)) {
            context.put("tree_name", paramsObj.getString(GenConstants.TREE_NAME));
        }
    }

    public static void setSubVelocityContext(Map<String,Object> context, GenTableVO genTable) {
        GenTableVO subTable = genTable.getSubTable();
        String subTableName = genTable.getSubTableName();
        String subTableFkName = genTable.getSubTableFkName();
        String subClassName = genTable.getSubTable().getClassName();
        String subTableFkClassName = StringUtils.convertToCamelCase(subTableFkName);

        context.put("subTable", subTable);
        context.put("subTableName", subTableName);
        context.put("subTableFkName", subTableFkName);
        context.put("subTableFkClassName", subTableFkClassName);
        context.put("subTableFkclassName", StringUtils.uncapitalize(subTableFkClassName));
        context.put("subClassName", subClassName);
        context.put("subclassName", StringUtils.uncapitalize(subClassName));
        context.put("subImportList", getImportList(genTable.getSubTable()));
    }

    /**
     * 获取模板信息
     *
     * @return 模板列表
     */
    public static List<String> getTemplateList(String tplCategory) {
        List<String> templates = new ArrayList<>();
        templates.add("vm/entity.java.vm");
        templates.add("vm/query-param.java.vm");
        templates.add("vm/save-param.java.vm");
        templates.add("vm/vo.java.vm");
        templates.add("vm/mapper.java.vm");
        templates.add("vm/service.java.vm");
        templates.add("vm/serviceImpl.java.vm");
        templates.add("vm/controller.java.vm");
        templates.add("vm/manager.java.vm");
        templates.add("vm/mapper.xml.vm");
        templates.add("vm/index.vue.vm");
        templates.add("vm/api.ts.vm");
        templates.add("vm/menu.sql.vm");
        return templates;
    }

    /**
     * 获取文件名
     */
    public static String getFileName(String template, GenTableVO genTable) {
        // 文件名称
        String fileName = "";
        // 包路径
        String packageName = genTable.getPackageName();
        // 模块名
        String moduleName = genTable.getModuleName();
        // 大写类名
        String className = genTable.getClassName();
        // 业务名称
        String businessName = genTable.getBusinessName();

        String javaPath = PROJECT_PATH + "/" + StringUtils.replace(packageName, ".", "/");
        String mybatisPath = MYBATIS_PATH + "/" + moduleName;

        if (template.contains("entity.java.vm")) {
            fileName = StringUtils.format("{}/domain/entity/{}.java", javaPath, className);
        } else if (template.contains("query-param.java.vm")) {
            fileName = StringUtils.format("{}/domain/param/{}QueryParam.java", javaPath, className);
        } else if (template.contains("save-param.java.vm")) {
            fileName = StringUtils.format("{}/domain/param/{}SaveParam.java", javaPath, className);
        } else if (template.contains("vo.java.vm")) {
            fileName = StringUtils.format("{}/domain/vo/{}VO.java", javaPath, className);
        } else if (template.contains("manager.java.vm")) {
            fileName = StringUtils.format("{}/manager/{}Manager.java", javaPath, className);
        } else if (template.contains("mapper.java.vm")) {
            fileName = StringUtils.format("{}/mapper/{}Mapper.java", javaPath, className);
        } else if (template.contains("service.java.vm")) {
            fileName = StringUtils.format("{}/service/{}Service.java", javaPath, className);
        } else if (template.contains("serviceImpl.java.vm")) {
            fileName = StringUtils.format("{}/service/impl/{}ServiceImpl.java", javaPath, className);
        } else if (template.contains("controller.java.vm")) {
            fileName = StringUtils.format("{}/controller/{}Controller.java", javaPath, className);
        } else if (template.contains("mapper.xml.vm")) {
            fileName = StringUtils.format("{}/{}Mapper.xml", mybatisPath, className);
        } else if (template.contains("menu.sql.vm")) {
            fileName = businessName + "Menu.sql";
        } else if (template.contains("api.ts.vm")) {
            fileName = businessName +"/"+genTable.getTableName().toLowerCase().replace("_","-") + ".ts";
        } else if (template.contains("index.vue.vm")) {
            fileName = businessName + "/index.vue";
        }
        return fileName;
    }

    /**
     * 获取项目文件路径
     *
     * @return 路径
     */
    public static String getProjectPath() {
        String packageName = GenConfig.instance.packageName;
        return "main/java/" + packageName.replace(".", "/") + "/";
    }

    /**
     * 获取包前缀
     *
     * @param packageName 包名称
     * @return 包前缀名称
     */
    public static String getPackagePrefix(String packageName) {
        int lastIndex = packageName.lastIndexOf(".");
        return StringUtils.substring(packageName, 0, lastIndex);
    }

    /**
     * 根据列类型获取导入包
     *
     * @param genTable 业务表对象
     * @return 返回需要导入的包列表
     */
    public static HashSet<String> getImportList(GenTableVO genTable) {
        List<GenTableColumnVO> columns = genTable.getColumns();
        GenTableVO subGenTable = genTable.getSubTable();
        HashSet<String> importList = new HashSet<>();
        if (StringUtils.isNotNull(subGenTable)) {
            importList.add("java.util.List");
        }
        for (GenTableColumnVO column : columns) {
            if (!GenUtils.isSuperColumn(column.getJavaType()) && GenConstants.TYPE_DATE.equals(column.getJavaType())) {
                importList.add("java.time.LocalDateTime");
            } else if (!GenUtils.isSuperColumn(column.getJavaType()) && GenConstants.TYPE_BIG_DECIMAL.equals(column.getJavaType())) {
                importList.add("java.math.BigDecimal");
            }
        }
        return importList;
    }

    /**
     * 获取权限前缀
     *
     * @param moduleName   模块名称
     * @param businessName 业务名称
     * @return 返回权限前缀
     */
    public static String getPermissionPrefix(String moduleName, String businessName) {
        return StringUtils.format("{}:{}", moduleName, businessName);
    }

    /**
     * 获取上级菜单ID字段
     *
     * @param paramsObj 生成其他选项
     * @return 上级菜单ID字段
     */
    public static String getParentMenuId(JSONObject paramsObj) {
        if (StringUtils.isNotEmpty(paramsObj) && paramsObj.containsKey(GenConstants.PARENT_MENU_ID)
                && StringUtils.isNotEmpty(paramsObj.getString(GenConstants.PARENT_MENU_ID))) {
            return paramsObj.getString(GenConstants.PARENT_MENU_ID);
        }
        return DEFAULT_PARENT_MENU_ID;
    }

    /**
     * 获取树编码
     *
     * @param paramsObj 生成其他选项
     * @return 树编码
     */
    public static String getTreecode(JSONObject paramsObj) {
        if (paramsObj.containsKey(GenConstants.TREE_CODE)) {
            return StringUtils.toCamelCase(paramsObj.getString(GenConstants.TREE_CODE));
        }
        return StringUtils.EMPTY;
    }

    /**
     * 获取树父编码
     *
     * @param paramsObj 生成其他选项
     * @return 树父编码
     */
    public static String getTreeParentCode(JSONObject paramsObj) {
        if (paramsObj.containsKey(GenConstants.TREE_PARENT_CODE)) {
            return StringUtils.toCamelCase(paramsObj.getString(GenConstants.TREE_PARENT_CODE));
        }
        return StringUtils.EMPTY;
    }

    /**
     * 获取树名称
     *
     * @param paramsObj 生成其他选项
     * @return 树名称
     */
    public static String getTreeName(JSONObject paramsObj) {
        if (paramsObj.containsKey(GenConstants.TREE_NAME)) {
            return StringUtils.toCamelCase(paramsObj.getString(GenConstants.TREE_NAME));
        }
        return StringUtils.EMPTY;
    }

    /**
     * 获取需要在哪一列上面显示展开按钮
     *
     * @param genTable 业务表对象
     * @return 展开按钮列序号
     */
    public static int getExpandColumn(GenTableVO genTable) {
        String options = genTable.getOptions();
        JSONObject paramsObj = JSONObject.parseObject(options);
        String treeName = paramsObj.getString(GenConstants.TREE_NAME);
        int num = 0;
        for (GenTableColumnVO column : genTable.getColumns()) {
            if (GenConstants.YES.equals(column.getIsList())) {
                num++;
                String columnName = column.getColumnName();
                if (columnName.equals(treeName)) {
                    break;
                }
            }
        }
        return num;
    }
}
